﻿namespace Microsoft.VisualStudio.TextTemplating.CommandLine
{
    using System;
    using System.ComponentModel;
    using System.Globalization;
    using System.IO;
    using System.Reflection;

    internal class DirectiveProcessorConverter : TypeConverter
    {
        public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if (sourceType == null)
            {
                throw new ArgumentNullException("sourceType");
            }
            return ((sourceType == typeof(string)) || base.CanConvertFrom(context, sourceType));
        }

        public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
        {
            if (value == null)
            {
                return null;
            }
            if (value.GetType() != typeof(string))
            {
                throw new InvalidOperationException(Resources.DirectiveProcessorConvertorFailed);
            }
            string str = (string) value;
            DirectiveProcessorRecord record = new DirectiveProcessorRecord();
            string[] strArray = str.Split(new string[] { "!" }, StringSplitOptions.None);
            record.Name = strArray[0];
            record.Class = strArray[1];
            Uri uri = null;
            try
            {
                uri = new Uri(strArray[2]);
            }
            catch (ArgumentNullException)
            {
                uri = null;
            }
            catch (UriFormatException)
            {
                uri = null;
            }
            if (File.Exists(strArray[2]))
            {
                record.CodeBase = strArray[2];
                return record;
            }
            if ((uri != null) && File.Exists(uri.LocalPath))
            {
                record.CodeBase = uri.LocalPath;
                return record;
            }
            AssemblyName name = new AssemblyName(strArray[2]);
            record.Assembly = name.FullName;
            return record;
        }

        public override bool GetCreateInstanceSupported(ITypeDescriptorContext context)
        {
            return true;
        }

        public override bool IsValid(ITypeDescriptorContext context, object value)
        {
            return true;
        }
    }
}

